import type { MenuResponse } from "@/services/modules";
import { createTree } from "../utils/createTree"
import { menu } from "@/services/api";
import router from ".";

const pages = () => {
    const views = import.meta.glob('./../views/**/*.vue')
    const result = []
    for (const key in views) {
        if (Object.prototype.hasOwnProperty.call(views, key)) {
            result.push({
                path: key.replace('../views', '').replace('.vue', '').replace('/index', ''),
                name: key.match(/\/([^\/]+)\/index\.vue/)![1],
                parent: key.match(/\/([^\/]+)\/([^\/]+)\/index\.vue/)![1],
                current: key.match(/\/([^\/]+)\/index\.vue/)![1],
                component: views[key],
                meta: {
                    auth: true
                }
            })
        }
    }
    return result
}

export const loadingRouter = async () => {
    let routes = []
    const views = pages()
    const { code, data } = await menu({ role: '' })
    let newViews: MenuResponse[] = []
    if (code === 200) {
        newViews = data.map(element => {
            return {
                ...views.find((view: any) => view.path === element.path),
                ...element,
            }
        });
    }

    routes = createTree(newViews, undefined, (node, parent): boolean => {
        return parent === undefined ? node.pid === 0 : parent && node.pid === parent.id
    })

    routes.forEach((item) => {
        // @ts-ignore
        router.addRoute(item)
    })

}